#include "seq_list.h"



//初始化
void SeqListInit(SL* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->capacity = ps->size = 0;
}

//判断空间是否足够
void SeqCheckCapacity(SL* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(ps->a, newCapacity * sizeof(SLDataType));
		if (tmp == NULL)
		{
			perror("realloc");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newCapacity;
	}
}

//打印
void SeqPrint(SL* ps)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}

//头插 
void SeqPushFront(SL* ps, SLDataType X)
{
	assert(ps);
	SeqCheckCapacity(ps);
	int end = ps->size - 1;
	while (end >= 0)
	{
		ps->a[end + 1] = ps->a[end];
		--end;
	}
	ps->a[0] = X;
	ps->size++;
	//SeqInsert(ps, 0, X);//后面有了在中间插入，可以在此直接复用
}

//头删,让后一个元素一次覆盖前一个元素
void SeqPopFront(SL* ps)
{
	assert(ps);
	int begin = 1;
	while (begin < ps->size)
	{
		ps->a[begin - 1] = ps->a[begin];
		++begin;
	}
	ps->size--;
}

//尾插
void SeqPushBack (SL* ps, SLDataType X)
{
	assert(ps);
	SeqCheckCapacity(ps);
	ps->a[ps->size] = X;
	ps->size++;
//	SeqInsert(ps, ps->size, X);//同理SeqPushFront; 
}


//尾删
void SeqPopBack(SL* ps)
{
	assert(ps);
	ps->size--;
}


//中间插入
void SeqInsert(SL* ps, int pos,SLDataType X)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	SeqCheckCapacity(ps);
	int end = ps->size - 1;
	while (pos <= end)
	{
		ps->a[end + 1] = ps->a[end];
		--end;
	}
	ps->a[pos] = X;
	ps->size++;
}


//在表中删除,也可以让头删，尾删处复用
void SeqErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	int begin = pos;
	while (begin < ps->size - 1)
	{
		ps->a[begin] = ps->a[begin + 1];
		++begin;
	}
	ps->size--;
}


//在表中查找
int SeqFind(SL* ps, SLDataType X)
{
	assert(ps);
	for (int i = 0; i < ps->size; ++i)
	{
		if (ps->a[i] == X)
		{
			return i;
		}
		return -1;
	}
 }

//在表中修改
void SeqModify(SL* ps, int pos, SLDataType X)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	ps->a[pos] = X;
}
